<script setup>
/**
 * 登录页面视图：
 * - 包装登录注册组件，显示全局成功/错误提示
 * - 已登录用户自动重定向到首页
 * - 通过 ?mode=register 控制初始模式
 */
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { isUserLoggedIn } from '../services/dataService'
import LoginRegister from '../components/LoginRegister.vue'

const route = useRoute()
const router = useRouter()

const successMessage = ref('')
const errorMessage = ref('')

// 根据查询参数决定初始模式
const initialMode = route.query.mode === 'register' ? 'register' : 'login'

onMounted(() => {
  // 已登录则直接跳转首页
  if (isUserLoggedIn()) {
    router.replace('/')
  }
})

// 处理登录成功事件
const handleLoginSuccess = () => {
  successMessage.value = '登录成功！'
  setTimeout(() => {
    successMessage.value = ''
  }, 2000)
}

// 处理注册成功事件
const handleRegisterSuccess = () => {
  successMessage.value = '注册成功！'
  setTimeout(() => {
    successMessage.value = ''
  }, 2000)
}

// 处理错误事件
const handleError = (errMsg) => {
  errorMessage.value = errMsg
  setTimeout(() => {
    errorMessage.value = ''
  }, 3000)
}
</script>

<template>
  <div class="login-container">
    <div class="login-box">
      <!-- 全局消息提示 -->
      <div v-if="successMessage" class="success-message">{{ successMessage }}</div>
      <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
      
      <!-- 使用抽象的登录注册组件 -->
      <LoginRegister 
        :initial-mode="initialMode"
        @login-success="handleLoginSuccess"
        @register-success="handleRegisterSuccess"
        @error="handleError"
      />
    </div>
  </div>
</template>

<style scoped>
.login-container {
  display: flex;
  min-height: 100vh;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  align-items: center;
  justify-content: center;
  padding: 20px;
}

.login-box {
  background: white;
  border-radius: 12px;
  padding: 40px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
}

.success-message {
  color: #38a169;
  font-size: 14px;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #c6f6d5;
  border-radius: 6px;
  border: 1px solid #9ae6b4;
  text-align: center;
}

.error-message {
  color: #e53e3e;
  font-size: 14px;
  margin-bottom: 15px;
  padding: 10px;
  background-color: #fed7d7;
  border-radius: 6px;
  border: 1px solid #feb2b2;
  text-align: center;
}

@media (max-width: 768px) {
  .login-box {
    padding: 30px 25px;
  }
}
</style>